﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
using System.Web.Security;
using System.Text;
using myomscl.Interfaces;
using myomscl.Presenters;
using myomscl.Utils;
namespace myomscl
{
    public partial class Login : System.Web.UI.Page, IUserView
    {
        string password;
        string userid;

        #region IUserView Members

        string IUserView.NewPassword
        {
            get { return txtNewPassword.Text; }
        }
        string IUserView.OldPassword
        {
            get { throw new NotImplementedException(); }
        }

        public event IUserPasswordUpdateById OnPasswordUpdateById;

        public event IUserPasswordUpdate OnPasswordUpdate;


        #endregion

        #region Page Events
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.AppendHeader("Pragma", "no-cache");
            Response.AppendHeader("Cache-Control", "no-cache");

            Response.CacheControl = "no-cache";
            Response.Expires = -1;

            Response.ExpiresAbsolute = new DateTime(1900, 1, 1);
            Response.Cache.SetCacheability(HttpCacheability.NoCache);


            if (Request.QueryString.AllKeys.Contains("key") &&
                Cache.Get(Request.QueryString["key"]) != null)
            {
                PresentationManager.RegisterView(typeof(UserDetailsPresenter), this, new WebSessionProvider());
                ResetPassword.Visible = true;
                DesignTester.Visible = false;
            }
            else
            {
                if (!IsPostBack)
                {
                    if (Request.Cookies["WorkflowAuthCookie"] != null)
                    {
                        HttpCookie cookie = Request.Cookies.Get("WorkflowAuthCookie");
                        string username = cookie.Values["Login"].ToString();
                        string password = cookie.Values["Pass"].ToString();                        
                        ctrlLogin.RememberMeSet = true;

                        if ((Session["logout"] == null || string.IsNullOrEmpty(Session["logout"].ToString())) &&
                            UserSecurity.Authenticate(username, password))
                        {
                            FormsAuthentication.RedirectFromLoginPage(username, true);
                        }
                    }
                }
            }
        }
        #endregion

        #region Control Events

        protected void ctrlLogin_Authenticate(object sender, AuthenticateEventArgs e)
        {
            e.Authenticated = UserSecurity.Authenticate(ctrlLogin.UserName, ctrlLogin.Password);
        }

        protected void SubmitButton_Click(object sender, EventArgs e)
        {
            if (this.IsValid)
            {
                //send email

                //Guid userKey = Guid.NewGuid();
                //Cache.Insert(userKey.ToString(), userid, null, DateTime.Now.AddDays(1), TimeSpan.Zero);


                //MailMessage msg = new MailMessage();
                //msg.Subject = "System Password recovery";
                //msg.To.Add(new MailAddress(ctrlPasswordRecovery.UserName));

                //StringBuilder sb = new StringBuilder();
                //sb.AppendLine("Beste Workflow gebruiker,");
                //sb.AppendLine(Environment.NewLine);
                //sb.AppendLine("U heeft gevraagd om uw wachtwoord opnieuw in te stellen. Als dit niet uw bedoeling is dan gelieve dit bericht te negeren.");
                //sb.AppendLine("U kunt hieronder op de link klikken om uw wachtwoord opnieuw in te stellen. De link is 24 uur na verzenden van dit bericht geldig.");
                //sb.AppendLine(Environment.NewLine);                
                //sb.AppendLine(string.Format("http://workflow.estate.nl/Login.aspx?key={0}", userKey));
                //sb.AppendLine(Environment.NewLine);
                //sb.AppendLine(Environment.NewLine);
                //sb.AppendLine("Met vriendelijke groeten,");
                //sb.AppendLine("Estate .");

                //msg.Body = sb.ToString();
                //msg.From = new MailAddress("workflow@estate.nl");
                //SmtpClient client = new SmtpClient("localhost");
                ////SmtpClient client = new SmtpClient("192.168.1.3");
                //client.Send(msg);
            }
        }

        protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
        {
            userid = UserSecurity.ValidateEmail(ctrlPasswordRecovery.UserName);
            args.IsValid = !string.IsNullOrEmpty(userid);
        }

        protected void ctrlLogin_LoggedIn(object sender, EventArgs e)
        {
            Response.Cookies.Remove("WorkflowAuthCookie");

            if (ctrlLogin.RememberMeSet)
            {
                HttpCookie myCookie = new HttpCookie("WorkflowAuthCookie");
                Response.Cookies.Add(myCookie);
                myCookie.Values.Add("Login", this.ctrlLogin.UserName.ToString());
                myCookie.Values.Add("Pass", this.ctrlLogin.Password.ToString());
                DateTime dtExpiry = DateTime.Now.AddDays(15);
                Response.Cookies["WorkflowAuthCookie"].Expires = dtExpiry;
            }
            else
            {
                DateTime dtExpiry = DateTime.Now.AddDays(-1);
                Response.Cookies["WorkflowAuthCookie"].Expires = dtExpiry;
            }


            FormsAuthentication.RedirectFromLoginPage(ctrlLogin.UserName, true);
        }

        protected void Reset_Click(object sender, EventArgs e)
        {
            if (Request.QueryString.AllKeys.Contains("key"))
            {
                var key = Request.QueryString["key"].ToString();
                int userId = Int32.Parse(Cache[key].ToString());
                if (OnPasswordUpdateById != null)
                {
                    OnPasswordUpdateById(userId);
                    Cache.Remove(key);
                    Response.Redirect("~/login.aspx");
                }
            }
        }

        #endregion

    }
}
